package arrAndstr;

import java.util.ArrayList;
import java.util.List;

/*
    92. 反转链表 II
    这道题如果left为1，则头指针是list最后一个元素，需要特殊处理
        我在这里犯了难，长时间没有写下去
        但是真的下代码对他特殊处理后，很多可以合并，代码也很简单
    收获：
        别嫌难，先做出来，再优化！
 */
public class T92 {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        ListNode node = head;

        node.next = new ListNode(5);

        reverseBetween(head, 1, 2);

    }

    public static ListNode reverseBetween(ListNode head, int left, int right) {
        if (left == right) return head;

        // 先把Node都放到list中，然后逆序拼接
        List<ListNode> list = new ArrayList<>();

        ListNode node = head;
        int num = 1;
        while (num <= right) {
            if (num >= left && num <= right) {
                list.add(node);
            }
            num++;
            node = node.next;
        }

        num = 1;
        int index = list.size() - 1;
        ListNode rightNode = list.get(index).next;
        if (left == 1) {
            head = list.get(index--);
        }
        node = head;
        while (true) {
            if (num < left-1) {
                node = node.next;
            } else if (num == right){
                node.next = rightNode;
                break;
            } else {
                node.next = list.get(index--);
                node = node.next;
            }
            num++;
        }

        return head;
    }
}












